﻿using Map;
using Microsoft.Xna.Framework;

namespace Map_Creator.MapInfo
{
    class CopyGrid : TileStructGrid
    {
        public override TileStruct this[int x, int y]
        {
            get
            {
                var tile = tiles[x, y];
                if (tile == null)
                {
                    return null;
                }
                var type = tile.GetType();
                switch (type.Name)
                {
                    case "Tile":
                        return tile;
                    case "AnimatedTile":
                        return tile;
                    case "AutoTile":
                        return new AutoTile4((tile as AutoTile4).AutoData);
                }
                return null;
            }
            set
            {
                base[x, y] = value;
            }
        }

        public CopyGrid(int x, int y)
        {
            tiles = new TileStruct[x,y];
            Size = new Point(x, y);
        }

        public static CopyGrid Copy(TileStructGrid grid, Rectangle sourceRect)
        {
            var copyGrid = new CopyGrid(sourceRect.Width,sourceRect.Height);
            for (int i = 0; i < sourceRect.Width; i++)
            {
                for (int j = 0; j < sourceRect.Height; j++)
                {
                    copyGrid.tiles[i, j] = grid[sourceRect.Left + i, sourceRect.Top + j];
                }
            }
            return copyGrid;
        }

        public void Paste(TileStructGrid grid, Rectangle destRectangle)
        {
            var size = new Point(tiles.GetLength(0), tiles.GetLength(1));
            for (int i = 0; i < destRectangle.Width; i++)
            {
                for (int j = 0; j < destRectangle.Height; j++)
                {
                    var tile = this[i % size.X, j % size.Y];
                    var pos = new Point(destRectangle.Left + i, destRectangle.Top + j);
                    grid[pos.X,pos.Y] = tile;
                    if (tile != null)
                    {
                        tile.UpdateValue(grid, pos);
                    }
                }
            }
        }
    }
}
